//
//  FindControl.m
//  FreeTime
//
//  Created by  on 16/8/25.
//  Copyright © 2016年 SRDZ.com. All rights reserved.
//

#import "FindControl.h"
#import "XFDraggableView.h"
#import "MWMainUserModel.h"
#import "MWLocationAutoView.h"
#import "MatchTorgetherView.h"
#import "MapTool.h"
#import "Header.h"
#import "ChooseView.h"
#define BTNSPACEWIDTH 20.0f
@interface FindControl ()<YHDraggableViewDelegate,UIAlertViewDelegate>
{
    NSInteger _distance;
    NSInteger _timerTimes;
    BOOL _isGotoAnotherVC;
}
@property (retain,nonatomic)NSMutableArray *exampleCardLabels;

@property (retain,nonatomic)NSMutableArray *allModels;

@property (retain,nonatomic)NSMutableArray *allCards;

@property (nonatomic,strong)NSMutableArray *loadedCards;

@property (nonatomic,assign)NSInteger cardsLoadedIndex;

@property (nonatomic,assign)NSInteger regainType;

@property (nonatomic,assign)BOOL isDownLoad;

@property (nonatomic,assign)BOOL canLocation;

@property (nonatomic,assign)NSInteger currentModelNum;

@property (nonatomic,strong)MWLocationAutoView *autoView;

@property (nonatomic,strong)MatchTorgetherView *matchTogetherView;

@property(nonatomic,strong)ChooseView *chooseView;

@property(nonatomic,strong)UIView *popView;

@property (nonatomic,strong)UIAlertView *locationAlert;

@property (nonatomic,assign)CGFloat maxBtnWidth,minBtnWidth,btnHeight;

@property (nonatomic,strong)UIButton *checkButton,*xButton;

@property(nonatomic,strong)UIButton *chatButton;

@property (nonatomic,strong)NSString *lastUserId;

@end

@implementation FindControl

static const int MAX_BUFFER_SIZE = 2;
#define CARD_WIDTH    WindowWidth-20
#define CARD_HEIGHT CARD_WIDTH+60
#define PHONE4CARD_WIDTH WindowWidth-20
#define PHONE4CARD_HEIGHT 265
#define AUTOSCROOL_WIDTH 220.0f
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
   
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationActive) name:UIApplicationDidBecomeActiveNotification object:nil];
    if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied){
        _canLocation = NO;
        for (UIView *view in self.view.subviews) {
            [view removeFromSuperview];
        }
        [self.autoView showOnView:self.view withText:@"请打开定位..."];
        [self.locationAlert show];
    }else{
        [[MapTool sharedMapTool] openGpsLocation];
        _canLocation = YES;
        //        self.timer.fireDate = [NSDate distantPast];
        //        _timerTimes = 0;
        //刷新UI
        [self setupView];
        if (_isGotoAnotherVC) {
            _isGotoAnotherVC = NO;
            NSString *distanceChange = [[NSUserDefaults standardUserDefaults] objectForKey:MW_CHANGEDISTANCE];
            if ([distanceChange integerValue] == 1) {
               
                [[NSUserDefaults standardUserDefaults] setValue:@"0" forKey:MW_CHANGEDISTANCE];
                for (UIView *view in self.view.subviews) {
                    if ([view isKindOfClass:[XFDraggableView class]]) {
                        [view removeFromSuperview];
                    }
                }
                [_autoView showOnView:self.view withText:@"正在努力搜索更多的人..."];
                [self requestInfomationWithDistance:_distance];
                
            }else{
                //更改性别时候的刷新页面
                if ([[[NSUserDefaults standardUserDefaults] valueForKey:MW_SEXCHANGE] integerValue]==1) {
                   // DLog(@"更改性别");
                    [[NSUserDefaults standardUserDefaults] setValue:@"2" forKey:MW_SEXCHANGE];
                    [[NSUserDefaults standardUserDefaults] synchronize];
                    for (UIView *view in self.view.subviews) {
                        if ([view isKindOfClass:[XFDraggableView class]]) {
                            [view removeFromSuperview];
                        }
                    }
                    [_autoView showOnView:self.view withText:@"正在努力搜索更多的人..."];
                    [self requestInfomationWithDistance:_distance];
                }else{
                    //DLog(@"正常切换页面");
                    BOOL haveView = NO;
                    for (UIView *view in self.view.subviews) {
                        if ([view isKindOfClass:[XFDraggableView class]]) {
                            haveView = YES;
                            break;
                        }
                    }
                    if (!haveView) {
                        
                        [self.autoView showOnView:self.view withText:@"正在努力搜索更多人..."];
                    }
                    if (!haveView && !self.isDownLoad) {
                        [self requestInfomationWithDistance:_distance];
                    }
                }
            }
        }else{
            //DLog(@"APP首次进入主页");
            //开始下载数据
            [self startDownLoad];
            
        }
        
    }
}
//从设置中返回
-(void)applicationActive
{
    //DLog(@"后台返回");
    if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied){
        for (UIView *view in self.view.subviews) {
            [view removeFromSuperview];
        }
        [self.autoView showOnView:self.view withText:@"请打开定位..."];
        [self.locationAlert show];
    }else{
        if (_canLocation) {
            BOOL haveView = NO;
            for (UIView *view in self.view.subviews) {
                if ([view isKindOfClass:[XFDraggableView class]]) {
                    haveView = YES;
                    break;
                }
            }
            if (!haveView) {
                [self.autoView showOnView:self.view withText:@"正在努力搜索更多的人..."];
            }
        }else{
            [self.autoView showOnView:self.view withText:@"请打开定位..."];
            [self.locationAlert show];
        }
    }
}
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
   
    _isGotoAnotherVC = YES;
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidBecomeActiveNotification object:nil];
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView == self.locationAlert) {
        if (buttonIndex == 0) {
            
        }else{
            if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
               // DLog(@"去设置");
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
            }
        }
    }
}
- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    [[NSUserDefaults standardUserDefaults] setValue:@"1" forKey:MW_CHANGESTATUS];
    
    self.navigationItem.title = @"喵会";
    
    _autoView = [MWLocationAutoView shardAutoView];
    
    self.view.backgroundColor =[UIColor whiteColor];
    
    //初始化数据
     _cardsLoadedIndex = 0;
    
     _currentModelNum = 0;
    
     _isGotoAnotherVC = NO;
    
     _distance = 10;
    
     _allCards = [NSMutableArray array];
    
     _loadedCards = [NSMutableArray array];
    
     _allModels = [NSMutableArray array];
    
     _exampleCardLabels = [NSMutableArray array];
    

    self.navigationItem.leftBarButtonItem=[UIBarButtonItem setupBarButtonItemWithText:@"筛选" Font:14 Target:self action:@selector(leftAction)];
}
-(void)leftAction{


    
    UIScreen *ss=[UIScreen mainScreen];
    
    
    CGFloat wid=[ss bounds].size.width;
    
    CGFloat height=[ss bounds].size.height;
    
    
   
        _chooseView=[[ChooseView alloc]initWithFrame:CGRectMake(0, 0, wid, height)];
        
        
      
    
   
    __weak  typeof (self)weakself=self;
    
    _chooseView.cancelBlcok=^(){

        [weakself.chooseView  removeFromSuperview];
    
    };
    
    _chooseView.confirmBlock=^(){
    
    [weakself.chooseView  removeFromSuperview];
    
    };
    
    

}

-(void)setIsDownLoad:(BOOL)isDownLoad
{
    _isDownLoad = isDownLoad;
    if (isDownLoad) {
        
        self.xButton.userInteractionEnabled = NO;
        self.checkButton.userInteractionEnabled = NO;
        self.chatButton.userInteractionEnabled=NO;
       
    }else{
        self.xButton.userInteractionEnabled = YES;
        self.checkButton.userInteractionEnabled = YES;
        self.chatButton.userInteractionEnabled=YES;
    }
}
-(void)startDownLoad
{
    [_autoView showOnView:self.view withText:@"正在努力搜索更多的人..."];
    
    [self requestInfomationWithDistance:_distance];
}
-(UIAlertView *)locationAlert
{
    if (!_locationAlert) {
        _locationAlert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"为了准确找到附近的用户，您需要在用户“设置”->“隐私”->“定位服务”中允许喵会进行定位" delegate:self cancelButtonTitle:@"稍后再说" otherButtonTitles:@"知道了", nil];
    }
    return _locationAlert;
}

-(CGFloat)maxBtnWidth
{
    CGFloat width;
    if (WindowWidth <= 320) {
        width = 60.0f;
    }else if (WindowWidth > 320 && WindowWidth <= 375){
        width = 70.0f;
    }else{
        width = 90.0f;
    }
    return width;
}
-(CGFloat)btnHeight
{
    CGFloat width;
    if (WindowWidth <= 320) {
        width = 55.0f;
    }else if (WindowWidth > 320 && WindowWidth <= 375){
        width = 70.0f;
    }else{
        width = 70.0f;
    }
    return width;
}
-(CGFloat)payHeight
{
    CGFloat width;
    if (WindowWidth <= 320) {
        width = 40.0f;
    }else if (WindowWidth > 320 && WindowWidth <= 375){
        width = 50.0f;
    }else{
        width = 50.0f;
    }
    return width;
}
-(CGFloat)payWidth
{
    CGFloat width;
    if (WindowWidth <= 320) {
        //width = 100.0f;
        width=90.0f;
    }else if (WindowWidth > 320 && WindowWidth <= 375){
        //width = 120.0f;
        width=110.f;
    }else{
        // width = 120.0f;
        width=110.0f;
    }
    return width;
}
-(UIButton *)xButton
{
    if (!_xButton) {
        
        //_xButton = [[UIButton alloc]initWithFrame:CGRectMake(WindowWidth / 2  - BTNSPACEWIDTH / 2 - self.maxBtnWidth, WindowHeight - self.btnHeight - self.maxBtnWidth-64, self.maxBtnWidth,self.maxBtnWidth)];
         _xButton = [[UIButton alloc]initWithFrame:CGRectMake(WindowWidth / 2  - BTNSPACEWIDTH / 2 - self.maxBtnWidth-self.payWidth/2, WindowHeight - self.btnHeight - self.maxBtnWidth-64, self.maxBtnWidth,self.maxBtnWidth)];
        NSLog(@"ssssnohao%f",WindowWidth / 2  - BTNSPACEWIDTH / 2 - self.maxBtnWidth-self.payWidth/2);
        
        [_xButton setImage:[UIImage imageNamed:@"taoyan"] forState:UIControlStateNormal];
        
        [_xButton setImage:[UIImage imageNamed:@"taoyan"] forState:UIControlStateHighlighted];
        
        [_xButton addTarget:self action:@selector(swipeLeft) forControlEvents:UIControlEventTouchUpInside];
    }
    return _xButton;
}
-(UIButton *)checkButton
{
    if (!_checkButton) {
        
        //_checkButton = [[UIButton alloc]initWithFrame:CGRectMake(WindowWidth / 2 + BTNSPACEWIDTH / 2, WindowHeight - self.btnHeight - self.maxBtnWidth-64, self.maxBtnWidth, self.maxBtnWidth)];
        _checkButton = [[UIButton alloc]initWithFrame:CGRectMake(WindowWidth / 2 + BTNSPACEWIDTH / 2+self.payWidth/2, WindowHeight - self.btnHeight - self.maxBtnWidth-64, self.maxBtnWidth, self.maxBtnWidth)];
        [_checkButton setImage:[UIImage imageNamed:@"aixin"] forState:UIControlStateNormal];
        
        [_checkButton setImage:[UIImage imageNamed:@"aixin"] forState:UIControlStateHighlighted];
        
        [_checkButton addTarget:self action:@selector(swipeRight) forControlEvents:UIControlEventTouchUpInside];
    }
    return _checkButton;
}
-(UIButton*)chatButton{
    if (!_chatButton) {
        
        _chatButton=[[UIButton alloc]initWithFrame:CGRectMake(WindowWidth / 2-self.payWidth/2, CGRectGetMidY(self.checkButton.frame) - self.payHeight / 2, self.payWidth, self.payHeight)];
        
        [_chatButton setImage:[UIImage imageNamed:@"button_chat_n"] forState:UIControlStateNormal];
        
        [_chatButton setImage:[UIImage imageNamed:@"button_chat_n"] forState:UIControlStateHighlighted];
        
        [_chatButton addTarget:self action:@selector(chatBtnAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _chatButton;
}
-(void)chatBtnAction{

    
    
    
    
    
    
    
    
    
}
-(void)setupView
{
    NSString *close = [[NSUserDefaults standardUserDefaults] objectForKey:MW_CLOSEPRICE];
    if ([close integerValue] == 1) {
        //取消按钮
        [self.view insertSubview:self.xButton atIndex:0];
        //选择按钮
        [self.view insertSubview:self.checkButton atIndex:0];
        [self.view insertSubview:self.chatButton atIndex:0];
    }else{
        //取消按钮
        [self.view insertSubview:self.xButton atIndex:0];
        //选择按钮
        [self.view insertSubview:self.checkButton atIndex:0];
        [self.view insertSubview:self.chatButton atIndex:0];
    }
}
- (void)loadCard
{
    if (_exampleCardLabels.count >0) {
        [_autoView dismiss];
        NSInteger numLoadedCardsCap = (([_exampleCardLabels count] > MAX_BUFFER_SIZE)?MAX_BUFFER_SIZE:[_exampleCardLabels count]);
        
        for (int i = 0 ; i<_exampleCardLabels.count; i++) {
            XFDraggableView *draggableView = [self createDraggableViewWithIndex:i];
            [_allCards addObject:draggableView];
            
            if (i<numLoadedCardsCap) {
                [_loadedCards addObject:draggableView];
            }
        }
        for (int i = 0; i < [_loadedCards count]; i++) {
            if (i>0) {
                [self changeCard];
                [self.view insertSubview:[_loadedCards objectAtIndex:i] belowSubview:[_loadedCards objectAtIndex:i-1]];
            }else{
                XFDraggableView *dragView = [_loadedCards objectAtIndex:i];
                [self.view addSubview:dragView];
            }
            //当前加载的个数
            _cardsLoadedIndex ++;
        }
    }
}
-(XFDraggableView *)createDraggableViewWithIndex:(NSInteger)index
{
    XFDraggableView *draggableView;
    if (WindowHeight <= 480) {
        draggableView = [[XFDraggableView alloc] initWithFrame:CGRectMake(10, 64 + 10, PHONE4CARD_WIDTH, PHONE4CARD_HEIGHT)];
    }else{
        draggableView = [[XFDraggableView alloc] initWithFrame:CGRectMake(10, 64+10, CARD_WIDTH, CARD_WIDTH + 50)];
    }
    draggableView.backgroundColor = [UIColor whiteColor];
    [draggableView setDraggalbleViewWithModel:self.exampleCardLabels[index]];
    draggableView.delegate = self;
    return draggableView;
}

-(void)cardView:(UIView *)card didselectHeadImageWithId:(NSString *)userId
{
    /*MWUserCenterViewController *userVC = [[MWUserCenterViewController alloc] init];
    userVC.targetId = userId;
    userVC.delegate = self;
    userVC.isPay = NO;*/
    //[self.navigationController pushViewController:userVC animated:NO];
}
#pragma mark -draggableDelegate
-(void)cardSwipedLeft:(UIView *)card
{
    [_loadedCards removeObjectAtIndex:0];
    if (_cardsLoadedIndex < [_allCards count]) {
        [_loadedCards addObject:[_allCards objectAtIndex:_cardsLoadedIndex]];
        _cardsLoadedIndex ++;
        [self changeCard];
        [self.view insertSubview:[_loadedCards objectAtIndex:(MAX_BUFFER_SIZE -1)] belowSubview:[_loadedCards objectAtIndex:(MAX_BUFFER_SIZE - 2)]];
    }
    //获取到当前model
    __block MWMainUserModel *model = _allModels[_currentModelNum];
    /*[[RequestHelper shareHelper]disLikePersonWithUserId:[NSString stringWithFormat:@"%@",model.targetUserId] Block:^(id data) {
        if ([data[@"status"] integerValue] == 1) {
            DLog(@"dislike");
        }else{
            DLog(@"tips %@",data[@"tips"]);
        }
    }];*/
    _currentModelNum ++;
    if (_currentModelNum == [_allCards count] - 1) {
        XFDraggableView *drag = [_allCards objectAtIndex:[_allCards count] - 1];
        CGRect frame = drag.frame;
        frame.origin.x -= 5;
        frame.origin.y -= 5;
        frame.size.width += 10;
        drag.frame = frame;
        drag.userInteractionEnabled = YES;
    }
    if (_currentModelNum  == [_allCards count]) {
        //重新获取数据
        MWMainUserModel *lastModel = [_allModels lastObject];
        self.lastUserId = lastModel.targetUserId;
        [self loadData];
    }
}
-(MatchTorgetherView *)matchTogetherView
{
    if (!_matchTogetherView) {
        _matchTogetherView = [MatchTorgetherView sharedMatchView];
    }
    return _matchTogetherView;
}
-(void)cardSwipedRight:(UIView *)card
{
    [_loadedCards removeObjectAtIndex:0];
    if (_cardsLoadedIndex < [_allCards count]) {
        [_loadedCards addObject:[_allCards objectAtIndex:_cardsLoadedIndex]];
        _cardsLoadedIndex ++;
        [self changeCard];
        [self.view insertSubview:[_loadedCards objectAtIndex:(MAX_BUFFER_SIZE -1)] belowSubview:[_loadedCards objectAtIndex:(MAX_BUFFER_SIZE - 2)]];
    }
    //获取到当前model
    __block MWMainUserModel *model = _allModels[_currentModelNum];
   // DLog(@"%li %li %li",(long)_cardsLoadedIndex,(long)_currentModelNum,(long)_allCards.count);
    _currentModelNum ++;
    /*[[RequestHelper shareHelper] likeWithTargetUserId:model.targetUserId Block:^(id data) {
        if ([data[@"status"] integerValue]==1) {
            if ([data[@"data"] isKindOfClass:[NSDictionary class]]) {
                __block NSDictionary *dict = data[@"data"];
                [self.matchTogetherView showWithImage:dict[@"nickName2_headImg"] targetName:dict[@"nickName2"]];
                __weak typeof(self) weakSelf = self;
                __block NSString *targetID = model.targetUserId;
                __block NSString *userName = dict[@"nickName2"];
                self.matchTogetherView.chatBlock = ^{
                    ChatViewController *chatVC = [[ChatViewController alloc] initWithChatter:targetID conversationType:eConversationTypeChat];
                    chatVC.userName = userName;
                    [weakSelf.navigationController pushViewController:chatVC animated:YES];
                };
                
            }
        }else{
            DLog(@"tips %@",data[@"tips"]);
        }
    }];*/
    
    //解决下面那个不能动
    if (_currentModelNum == [_allCards count] - 1) {
        XFDraggableView *drag = [_allCards objectAtIndex:[_allCards count] - 1];
        CGRect frame = drag.frame;
        frame.origin.x -= 5;
        frame.origin.y -= 5;
        frame.size.width += 10;
        drag.frame = frame;
        drag.userInteractionEnabled = YES;
    }
    
    if (_currentModelNum  == [_allCards count]) {
        //重新获取数据
        MWMainUserModel *lastModel = [_allModels lastObject];
        self.lastUserId = lastModel.targetUserId;
        [self loadData];
    }
}
-(void)changeCard
{
    XFDraggableView *secDragView = [_loadedCards objectAtIndex:(MAX_BUFFER_SIZE - 1)];
    XFDraggableView *firDragView = [_loadedCards objectAtIndex:(MAX_BUFFER_SIZE - 2)];
    firDragView.userInteractionEnabled = YES;
    secDragView.userInteractionEnabled = NO;
    CGRect frame = secDragView.frame;
    
    firDragView.frame = frame;
    
    frame.origin.y += 5;
    frame.origin.x += 5;
    frame.size.width -= 10;
    secDragView.frame = frame;
}
- (void)userIsMoveToLeft
{
    [self swipeLeft];
}
-(void)userIsMoveToRight
{
    [self swipeRight];
}
-(void)swipeLeft
{
    XFDraggableView *drag = [_loadedCards firstObject];
    drag.overlayView.mode = CGOverlayViewModeLeft;
    [UIView animateWithDuration:0.2 animations:^{
        drag.overlayView.alpha = 1;
    }];
    [drag leftClickAction];
}
-(void)swipeRight
{
    XFDraggableView *drag = [_loadedCards firstObject];
    drag.overlayView.mode = CGOverlayViewModeRight;
    [UIView animateWithDuration:0.2 animations:^{
        
        drag.overlayView.alpha = 1;
    }];
    [drag rightClickAction];
}
-(void)loadData
{
    [_autoView showOnView:self.view withText:@"正在努力搜索更多的人..."];
    [self requestInfomationWithDistance:_distance];
}
-(void)requestInfomationWithDistance:(NSInteger)distance
{
    self.isDownLoad = YES;
    
    if ([[[NSUserDefaults standardUserDefaults] valueForKey:MW_SEXCHANGE] integerValue]==1) {
        
        [[NSUserDefaults standardUserDefaults] setValue:@"2" forKey:MW_SEXCHANGE];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
   /* [[RequestHelper shareHelper] loadUsersWithPage:1 distance:distance Block:^(id data) {
        if ([data[@"status"] integerValue]==1) {
            NSDictionary *dataList = data[@"data"];
            _cardsLoadedIndex = 0;
            _currentModelNum = 0;
            [_allCards removeAllObjects];
            [_loadedCards removeAllObjects];
            [_allModels removeAllObjects];
            [_exampleCardLabels removeAllObjects];
            for (NSDictionary *dict in dataList[@"dataList"]) {
                MWMainUserModel *model = [[MWMainUserModel alloc] init];
                [model setValuesForKeysWithDictionary:dict];
                if ([model.targetUserId integerValue] != [self.lastUserId integerValue]) {
                    [_exampleCardLabels addObject:model];
                    [_allModels addObject:model];
                }
            }
            [self loadCard];
        }
        if ([data[@"status"] integerValue] == 0) {
            DLog(@"%@",data[@"tips"]);
            [_autoView showOnView:self.view withText:@"正在努力搜索中...貌似附近没有更多的人了..."];
        }
        self.isDownLoad = NO;
    }];*/
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    
}

-(void)touchesBegan:(NSSet*)touches withEvent:(UIEvent *)event
{
    [self.tabBarController.tabBar setHidden:NO];
}
@end
